using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Navigation;

namespace App1
{
    /// <summary>
    /// 下载任务数据模型
    /// </summary>
    public class DownloadTask : INotifyPropertyChanged
    {
        private string _fileName;
        private string _filePath;
        private double _progress;
        private string _progressText;
        private string _speedText;
        private bool _isPaused;
        private CancellationTokenSource _cancellationTokenSource;

        public string FileName
        {
            get => _fileName;
            set => SetProperty(ref _fileName, value);
        }

        public string FilePath
        {
            get => _filePath;
            set => SetProperty(ref _filePath, value);
        }

        public double Progress
        {
            get => _progress;
            set => SetProperty(ref _progress, value);
        }

        public string ProgressText
        {
            get => _progressText;
            set => SetProperty(ref _progressText, value);
        }

        public string SpeedText
        {
            get => _speedText;
            set => SetProperty(ref _speedText, value);
        }

        public bool IsPaused
        {
            get => _isPaused;
            set => SetProperty(ref _isPaused, value);
        }

        public CancellationTokenSource CancellationTokenSource
        {
            get => _cancellationTokenSource;
            set => _cancellationTokenSource = value;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            if (Equals(storage, value)) return false;
            storage = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    /// 下载管理器
    /// </summary>
    public class DownloadManager
    {
        private readonly DispatcherQueue _dispatcherQueue;
        private int _maxThreads = 4; // 默认最大线程数
        private double _speedLimit = 0; // 默认不限速 (MB/S)
        private readonly SemaphoreSlim _threadSemaphore;
        private readonly ObservableCollection<DownloadTask> _downloadTasks;

        public ObservableCollection<DownloadTask> DownloadTasks => _downloadTasks;

        public int MaxThreads
        {
            get => _maxThreads;
            set
            {
                _maxThreads = value;
                // 更新信号量
                if (_threadSemaphore != null)
                {
                    // 这里简化处理，实际应用中可能需要更复杂的逻辑
                }
            }
        }

        public double SpeedLimit
        {
            get => _speedLimit;
            set => _speedLimit = value;
        }

        public DownloadManager(DispatcherQueue dispatcherQueue)
        {
            _dispatcherQueue = dispatcherQueue;
            _downloadTasks = new ObservableCollection<DownloadTask>();
            _threadSemaphore = new SemaphoreSlim(_maxThreads, _maxThreads);
        }

        /// <summary>
        /// 添加下载任务
        /// </summary>
        public async Task AddDownloadTask(string url, string savePath)
        {
            var fileName = Path.GetFileName(url);
            var filePath = Path.Combine(savePath, fileName);

            var task = new DownloadTask
            {
                FileName = fileName,
                FilePath = filePath,
                Progress = 0,
                ProgressText = "准备下载...",
                SpeedText = "0 MB/S",
                IsPaused = false,
                CancellationTokenSource = new CancellationTokenSource()
            };

            await _dispatcherQueue.EnqueueAsync(() =>
            {
                _downloadTasks.Add(task);
            });

            // 开始下载
            StartDownloadTask(task, url);
        }

        /// <summary>
        /// 开始下载任务
        /// </summary>
        private async void StartDownloadTask(DownloadTask task, string url)
        {
            await _threadSemaphore.WaitAsync();
            try
            {
                using (var client = new WebClient())
                {
                    // 处理进度更新
                    client.DownloadProgressChanged += (sender, e) =>
                    {
                        _dispatcherQueue.TryEnqueue(() =>
                        {
                            task.Progress = e.ProgressPercentage;
                            task.ProgressText = $"{e.ProgressPercentage}% ({FormatFileSize(e.BytesReceived)} / {FormatFileSize(e.TotalBytesToReceive)})";

                            // 计算下载速度
                            var speed = e.BytesPerSecond / (1024.0 * 1024.0); // MB/S
                            task.SpeedText = $"{speed:F2} MB/S";
                        });
                    };

                    // 处理下载完成
                    client.DownloadFileCompleted += (sender, e) =>
                    {
                        _dispatcherQueue.TryEnqueue(() =>
                        {
                            if (e.Cancelled)
                            {
                                task.ProgressText = "已取消";
                            }
                            else if (e.Error != null)
                            {
                                task.ProgressText = "下载错误: " + e.Error.Message;
                            }
                            else
                            {
                                task.Progress = 100;
                                task.ProgressText = "下载完成";
                            }
                        });
                        _threadSemaphore.Release();
                    };

                    // 开始下载
                    await client.DownloadFileTaskAsync(new Uri(url), task.FilePath, task.CancellationTokenSource.Token);
                }
            }
            catch (OperationCanceledException)
            {
                _dispatcherQueue.TryEnqueue(() =>
                {
                    task.ProgressText = "已取消";
                });
                _threadSemaphore.Release();
            }
            catch (Exception ex)
            {
                _dispatcherQueue.TryEnqueue(() =>
                {
                    task.ProgressText = "下载错误: " + ex.Message;
                });
                _threadSemaphore.Release();
            }
        }

        /// <summary>
        /// 暂停/继续下载任务
        /// </summary>
        public void TogglePauseDownloadTask(DownloadTask task)
        {
            if (task.IsPaused)
            {
                // 继续下载
                task.IsPaused = false;
                var newCts = new CancellationTokenSource();
                task.CancellationTokenSource = newCts;
                // 重新开始下载（简化处理，实际应用中应支持断点续传）
                var url = "";
                StartDownloadTask(task, url); // 这里需要传递实际的URL
            }
            else
            {
                // 暂停下载
                task.IsPaused = true;
                task.CancellationTokenSource?.Cancel();
            }
        }

        /// <summary>
        /// 取消下载任务
        /// </summary>
        public void CancelDownloadTask(DownloadTask task)
        {
            task.CancellationTokenSource?.Cancel();
            _dispatcherQueue.TryEnqueue(() =>
            {
                _downloadTasks.Remove(task);
            });
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            else if (bytes < 1024 * 1024)
                return $"{(bytes / 1024.0):F2} KB";
            else if (bytes < 1024 * 1024 * 1024)
                return $"{(bytes / (1024.0 * 1024.0)):F2} MB";
            else
                return $"{(bytes / (1024.0 * 1024.0 * 1024.0)):F2} GB";
        }
    }

    /// <summary>
    /// 下载管理页面
    /// </summary>
    public sealed partial class DownloadManagerPage : Page
    {
        private DownloadManager _downloadManager;
        private SettingsPage _settingsPage;

        public DownloadManagerPage()
        {
            this.InitializeComponent();
            _downloadManager = new DownloadManager(DispatcherQueue.GetForCurrentThread());
            DownloadTasksListView.ItemsSource = _downloadManager.DownloadTasks;

            // 注册设置变更事件
            _settingsPage = new SettingsPage();
            _settingsPage.SettingsChanged += OnSettingsChanged;
        }

        private void OnSettingsChanged(object sender, SettingsChangedEventArgs e)
        {
            // 更新下载管理器的设置
            _downloadManager.MaxThreads = e.MaxThreads;
            _downloadManager.SpeedLimit = e.SpeedLimit;
        }

        private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is DownloadTask task)
            {
                _downloadManager.TogglePauseDownloadTask(task);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.CommandParameter is DownloadTask task)
            {
                _downloadManager.CancelDownloadTask(task);
            }
        }
    }

    /// <summary>
    /// 播放/暂停图标转换器
    /// </summary>
    public class PlayPauseGlyphConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is bool isPaused && isPaused)
                return ""; // 播放图标
            else
                return ""; // 暂停图标
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 设置变更事件参数
    /// </summary>
    public class SettingsChangedEventArgs : EventArgs
    {
        public int MaxThreads { get; set; }
        public double SpeedLimit { get; set; }
    }
}